package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.ArrayList;
import java.util.List;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.zzyl.common.core.domain.BaseEntity;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.IotMsgNotifyData;
import com.zzyl.nursing.dto.IotMsgService;
import com.zzyl.nursing.mapper.DeviceMapper;
import org.hibernate.validator.internal.util.stereotypes.ThreadSafe;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import java.util.Arrays;
import java.util.Map;

import static com.zzyl.common.constant.CacheConstants.IOT_DEVICE_LAST_DATA;

/**
 * 设备数据Service业务层处理
 *
 * @author ruoyi
 * @date 2025-03-01
 */
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;

    @Autowired
    private DeviceMapper deviceMapper;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return getById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public List<DeviceData> selectDeviceDataList(DeviceData deviceData) {
        return deviceDataMapper.selectDeviceDataList(deviceData);
    }

    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return save(deviceData) ? 1 : 0;
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return updateById(deviceData) ? 1 : 0;
    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return removeByIds(Arrays.asList(ids)) ? 1 : 0;
    }

    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return removeById(id) ? 1 : 0;
    }

    @Override
    //添加事务
    @org.springframework.transaction.annotation.Transactional
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //根据设备标识码查询设备，把基本设备信息查询带device对象当中
        String deviceId = iotMsgNotifyData.getHeader().getDeviceId();
        Device device = deviceMapper.selectOne(Wrappers.<Device>lambdaQuery().eq(Device::getIotId, deviceId));
        //判断数据库中是否有该设备
        if (ObjectUtil.isEmpty(device)) {
            log.error("设备不存在");
            return;
        }
        //把传输来的数据信息拿出来
        List<IotMsgService> services = iotMsgNotifyData.getBody().getServices();

        //遍历设备信息当中的属性
        for (IotMsgService service : services) {
            //拿到设备信息当中的核心信息
            Map<String, Object> properties = service.getProperties();
            if (ObjectUtil.isEmpty(properties)) {
                continue;
            }
            //日期时区转换
            LocalDateTime activeTime = LocalDateTimeUtil.parse(service.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime eventTime = activeTime.atZone(ZoneId.from(ZoneOffset.UTC)).withZoneSameInstant(ZoneId.of("Asia/Shanghai")).toLocalDateTime();

            List<DeviceData> list = new ArrayList<>(properties.size());
            //对设备当中的属性进行遍历
            properties.forEach((k, v) -> {
                DeviceData build = DeviceData.builder()
                        .iotId(deviceId)
                        .functionId(k)
                        .dataValue(v.toString())
                        .alarmTime(eventTime)
                        .accessLocation(device.getRemark())
                        .build();
                BeanUtil.copyProperties(device, build, "id", "createBy", "createTime", "updateBy", "updateTime");
                list.add(build);
            });
            this.saveBatch(list);
            redisTemplate.opsForHash().put(IOT_DEVICE_LAST_DATA, deviceId, list);
        }

    }
}
